import logging

from google.appengine.api import urlfetch
from StringIO import StringIO
import struct

def getImageInfo(data):
    data = str(data)
    size = len(data)
    height = -1
    width = -1
    content_type = ''

    # handle GIFs
    if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
        # Check to see if content_type is correct
        content_type = 'image/gif'
        w, h = struct.unpack("<HH", data[6:10])
        width = int(w)
        height = int(h)

    # See PNG v1.2 spec (http://www.cdrom.com/pub/png/spec/)
    # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
    # and finally the 4-byte width, height
    elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
          and (data[12:16] == 'IHDR')):
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[16:24])
        width = int(w)
        height = int(h)

    # Maybe this is for an older PNG version.
    elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[8:16])
        width = int(w)
        height = int(h)

    # handle JPEGs
    elif (size >= 2) and data.startswith('\377\330'):
        content_type = 'image/jpeg'
        jpeg = StringIO(data)
        jpeg.read(2)
        b = jpeg.read(1)
        try:
            while (b and ord(b) != 0xDA):
                while (ord(b) != 0xFF): b = jpeg.read(1)
                while (ord(b) == 0xFF): b = jpeg.read(1)
                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                    jpeg.read(3)
                    h, w = struct.unpack(">HH", jpeg.read(4))
                    break
                else:
                    jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                b = jpeg.read(1)
            width = int(w)
            height = int(h)
        except struct.error:
            pass
        except ValueError:
            pass

    return content_type, width, height


class SiteImage():
    def set(self, url):
    	self._width = 0
        self._height = 0
        self.isdownloaded = True
	
        try: 
            # When deployed 
            from google.appengine.runtime import DeadlineExceededError 
        except ImportError: 
            # In the development server 
            from google.appengine.runtime.apiproxy_errors import DeadlineExceededError 
	
        try:
            #logging.debug(url)
            result = urlfetch.fetch(url)
            if result.status_code == 200:
                data = result.content
            else:
                self.isdownloaded = False
    	except DeadlineExceededError:
            self.isdownloaded = False
            return
        except urlfetch.InvalidURLError:
            self.isdownloaded = False
            return
        except:
            self.isdownloaded = False
            return

        if self.isdownloaded is True:
            #logging.debug(str(len(data)))
            self.contentType, self._width, self._height = getImageInfo(data)
            self.url = url
            self.area = self._width * self._height
            self.isdownloaded = True
            #logging.debug('IMG: ' + str(self._width) + " " + str(self._height))
            if (self._width > (2.5 * self._height)) or (self._height > (2.5*self._width)) or self._width < 20 or self._height < 20:
                self.isadvers = True
            else:
                self.isadvers = False
            #logging.debug(str(self.isdownloaded))

    def getSize(self):
        return (self._width, self._height)

    def getWidth(self):
        return self._width

    def getHeight(self):
        return self._height

    def getArea(self):
        return self.area

    def IsAdvers(self):
        return self.isadvers

    def getUrl(self):
        return self.url

    def IsDownloaded(self):
        return self.isdownloaded

